import React from "react";
import {List, Badge} from "antd-mobile";
import {connect} from "react-redux";
import {getLastMsg} from "../../utils";

@connect(
  state => state
)
class Msg extends React.Component {

  render () {
    const userId = this.props.user._id;
    const userInfo = this.props.chatMsg.users;
    if (!userId) {
      return null;
    }
    let msgMap = {};
    this.props.chatMsg.chatMsgList.forEach(v => {
      if (userId !== v.from) {
        const k = v.chatId;
        msgMap[k] ? msgMap[k].push(v) : msgMap[k] = [v]
      }
    });
    const msgList = Object.values(msgMap).sort((a, b) => {
      return a[a.length - 1].create_time - b[b.length - 1].create_time < 0;
    });
    const Item = List.Item;
    const Brief = List.Item.Brief;
    return (
      <div>
        {
          msgList.map(arr => {
            const msg = getLastMsg(arr);
            const unread = arr.filter(v => !v.read).length;
            const msgInfo = arr[0];
            const tgtId = msgInfo.from;
            if (!(userInfo && userInfo[tgtId])) {
              return null;
            }
            const name = userInfo[tgtId].username;
            const avatar = userInfo[tgtId].avatar;
            return (
              <List key={msgInfo._id}>
                <Item
                  thumb={require(`../../assets/avatar/${avatar}.png`)}
                  extra={<Badge text={unread}/>}
                  arrow="horizontal"
                  onClick={()=> this.props.history.push(`/chat/${tgtId}`)}>
                  {msg}
                  <Brief>{name}</Brief>
                </Item>
              </List>
            );
          })
        }
      </div>
    );
  }
}

export default Msg;
